package com.baoyi.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.baoyi.content.content;
import com.baoyi.pooke.BaoyiApplication;

public class DiskImageCache extends ImageCache {

	@Override
	public Bitmap get(Object key) {
		String pic = key.toString();
		String filess = Utils.getMD5Str(pic);
		File fileitem = new File(content.pookedir + filess + ".jpg");
		Bitmap image = null;
		// 如果磁盘不存在，则在内存中查找
		if (!fileitem.exists()) {
			Log.d(BaoyiApplication.TAG, "缓存中没有图片");
			image = super.get(key);
		} else {
			FileInputStream inputStream;
			try {
				inputStream = new FileInputStream(fileitem);
				image = BitmapFactory.decodeStream(inputStream);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			// 如果磁盘查找错误，则在内存中查找
			if (null == image) {
				image = super.get(key);
			}
		}

		return image;

	}



	@Override
	public Bitmap put(String key, Bitmap value) {
		String filess = Utils.getMD5Str(key);
		// 下载远程图片到本地,如果磁盘缓存失败，缓存到内容
		File fileitem = new File(content.pookedir + filess + ".jpg");
		if (fileitem.exists() && fileitem.length() > 100) {
			Log.d(BaoyiApplication.TAG, "磁盘中存在该文件");
		} else {
			Log.d(BaoyiApplication.TAG, "网络图片" + key);
			Log.d(BaoyiApplication.TAG, "缓存文件到磁盘");
			URL url;
			try {
				url = new URL(key);
				URLConnection conn = url.openConnection();
				conn.setDoInput(true);
				int length = (int) conn.getContentLength();
				InputStream is = conn.getInputStream();
				if (length != -1) {
					FileOutputStream output = new FileOutputStream(fileitem);
					byte buffer[] = new byte[6 * 1024];
					int temp1;
					while ((temp1 = is.read(buffer)) != -1) {
						output.write(buffer, 0, temp1);
					}
					output.flush();
				}
			} catch (MalformedURLException e) {
				super.put(key, value);
			} catch (IOException e) {
				super.put(key, value);
			}
		}
		return value;
	}
}
